package com.lovefreedom.psi.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.lovefreedom.psi.bean.Category;

public class Tree {
	//存放排好次序的树列表
	List treeList = new ArrayList();

	public List getTreeList() {
		return treeList;
	}
	public void setTreeList(List treeList) {
		this.treeList = treeList;
	}
	//构造方法初始化
	public void Tree() {

	}
    //树的递归算法，参数为列表数据和根节点。将数据按次序放入treeList列表中。
	public void recursionFn(List list, Category node) {
		if (hasChild(list, node)) {
			treeList.add(node);
			List childList = getChildList(list, node);
			Iterator it = childList.iterator();
			while (it.hasNext()) {
				Category n = (Category) it.next();
				recursionFn(list, n);
			}
		} else {
			treeList.add(node);
		}
	}
	//判断是否有子节点
	public boolean hasChild(List list, Category node) { 
		return getChildList(list, node).size() > 0 ? true : false;
	}
	//得到子节点列表
	public List getChildList(List list, Category node) { 
		List li = new ArrayList();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			Category n = (Category) it.next();
			if (n.getParentId() == node.getId()) {
				li.add(n);
			}
		}
		return li;
	}
}

